package com.yzx.lifeassistants.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.PartTimeInfo;
import com.yzx.lifeassistants.model.IQueryPartTimeInfo;
import com.yzx.lifeassistants.model.callback.IQueryPartTimeInfoCB;
import com.yzx.lifeassistants.model.impl.QueryPartTimeInfoImpl;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 兼职详情
 * @author: yzx
 * @time: 2016-4-6 下午3:38:17
 */
@SuppressLint({ "SetJavaScriptEnabled", "InflateParams" })
public class PartTimeInfoActivity extends BaseActivity implements
		OnClickListener {
	private ImageButton backBtn;// 返回按钮
	private ImageButton moreBtn;// 更多按钮
	private TextView titleTV;// 标题
	private TextView placeTV;// 地点
	private TextView timeTV;// 时间
	private TextView companyTV;// 公司
	private TextView industryTV;// 行业
	private TextView companyTypeTV;// 公司类型
	private TextView companyScaleTV;// 公司规模
	private WebView detailWV;// 详细内容

	private String url;// URL
	private String telUrl;// 手机URL
	private CircularLoadingDialog dialog;// 加载框
	private Handler handler;//
	private IQueryPartTimeInfoCB queryCallBack;// 回调
	private IQueryPartTimeInfo queryPartTimeInfo;// 查询
	private String html;//

	private View contentView;// 更多弹框
	private AlertDialog theDialog;// 更多弹框
	private ImageView telIV;// 手机号码
	private TextView noTelTV;// 暂无手机号码
	private Bitmap bitmap;
	private AsyncTask<Void, Void, Void> task;
	/**
	 * @Description: Html页面头部
	 */
	public static final String HTML_HEAD = "<!DOCTYPE html>"
			+ "<head>"
			+ "<meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=0.8, maximum-scale=1.0, user-scalable=no' />"
			+ "<meta http-equiv='Content-Type' content='text/html; charset=gb2312' />"
			+ "</head>" + "<body>";

	/**
	 * @Description: Html页面尾部
	 */
	public static final String HTML_END = "</body>"
			+ "<script>  document.body.style.lineHeight = 1.5 </script>"
			+ "</html>";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_part_time_info);
		init();
		initView();
		setListener();
		initTelDialog();
		initData();
	}

	/**
	 * 
	 * @Description: 初始化
	 */
	private void init() {
		Intent intent = getIntent();
		if (null == intent) {
			url = "";
		} else {
			url = intent.getStringExtra("PART_TIME_INFO_URL");
		}
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.part_time_info_back_btn);
		moreBtn = (ImageButton) findViewById(R.id.part_time_info_more_btn);
		titleTV = (TextView) findViewById(R.id.part_time_info_title_tv);
		placeTV = (TextView) findViewById(R.id.part_time_info_place_tv);
		timeTV = (TextView) findViewById(R.id.part_time_info_time_tv);
		companyTV = (TextView) findViewById(R.id.part_time_info_company_tv);
		industryTV = (TextView) findViewById(R.id.part_time_info_industry_tv);
		companyTypeTV = (TextView) findViewById(R.id.part_time_info_company_type_tv);
		companyScaleTV = (TextView) findViewById(R.id.part_time_info_company_scale_tv);
		detailWV = (WebView) findViewById(R.id.part_time_info_detail_wv);
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		moreBtn.setOnClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化更多对话框
	 */
	private void initTelDialog() {
		task = new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				URL myFileUrl = null;
				try {
					myFileUrl = new URL(telUrl);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
				try {
					HttpURLConnection conn = (HttpURLConnection) myFileUrl
							.openConnection();
					conn.setRequestMethod("GET");
					// 必须设置false，否则会自动redirect到Location的地址
					conn.setInstanceFollowRedirects(false);
					conn.addRequestProperty("Referer", url);
					conn.connect();
					InputStream is = conn.getInputStream();
					bitmap = BitmapFactory.decodeStream(is);
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				telIV.setImageBitmap(bitmap);
			}

		};
		// 弹框
		theDialog = new AlertDialog.Builder(this).create();
		theDialog.setCanceledOnTouchOutside(true);
		contentView = LayoutInflater.from(this).inflate(R.layout.dialog_tel,
				null);
		telIV = (ImageView) contentView.findViewById(R.id.dialog_tel_iv);
		noTelTV = (TextView) contentView.findViewById(R.id.dialog_no_tel_tv);
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		handler = new Handler();
		queryCallBack = new IQueryPartTimeInfoCB() {

			@Override
			public void querySuccess(final PartTimeInfo info) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						telUrl = info.getTelUrl();
						titleTV.setText(info.getTitle());
						placeTV.setText(info.getPlace());
						timeTV.setText(info.getTime());
						companyTV.setText(info.getCompany());
						if (!info.getIsVerify()) {
							companyTV.setCompoundDrawables(null, null, null,
									null);
						}
						industryTV.setText(info.getIndustry());
						companyTypeTV.setText(info.getCompanyType());
						companyScaleTV.setText(info.getCompanyScale());
						html = HTML_HEAD + info.getDetail() + HTML_END;
						detailWV.loadDataWithBaseURL(null, html, "text/html",
								"utf-8", null);
					}
				});
			}

			@Override
			public void queryError(final int code) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						switch (code) {
						case IQueryPartTimeInfoCB.RESULR_NULL: {
							showToast("获取失败，请确认网络连接后刷新重试~");
							break;
						}
						case IQueryPartTimeInfoCB.QUERY_ERROR: {
							showToast("获取异常，请确认网络连接后刷新重试~");
							break;
						}
						default:
							break;
						}
					}
				});
			}
		};
		queryPartTimeInfo = new QueryPartTimeInfoImpl(this, queryCallBack);

		WebSettings webSettings = detailWV.getSettings();
		webSettings.setJavaScriptEnabled(true);// 支持JS
		detailWV.getSettings().setSupportZoom(true);// 支持屏幕缩放
		detailWV.getSettings().setBuiltInZoomControls(true);
		detailWV.getSettings().setDisplayZoomControls(false);// 不显示webview缩放按钮
		webSettings.setAllowContentAccess(true);
		webSettings.setAppCacheEnabled(false);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		detailWV.setWebChromeClient(new WebChromeClient() {

			@Override
			public void onProgressChanged(WebView view, int newProgress) {

				if (newProgress == 100) {

				}
				super.onProgressChanged(view, newProgress);
			}

		});

		queryPartTimeInfo();
	}

	/**
	 * 
	 * @Description: 获取通知详情
	 */
	private void queryPartTimeInfo() {
		if (null == url || "".equals(url)) {
			showToast("获取异常，请确认网络连接后刷新重试~");
		} else {
			dialog.show();
			queryPartTimeInfo.queryPartTimeInfo(url);
		}
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.part_time_info_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.part_time_info_more_btn: {// 更多
			if (null == telUrl || "".equals(telUrl)) {
				telIV.setVisibility(View.GONE);
				noTelTV.setVisibility(View.VISIBLE);
			} else if (null == bitmap) {// 若无图片则去生成
				noTelTV.setVisibility(View.GONE);
				telIV.setVisibility(View.VISIBLE);
				task.execute();
			} else {
				noTelTV.setVisibility(View.GONE);
				telIV.setVisibility(View.VISIBLE);
			}
			theDialog.show();
			theDialog.setContentView(contentView);
			theDialog.getWindow().setGravity(Gravity.CENTER);
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message) {
		ToastUtils.showAlertToast(this, message, R.id.part_time_info_top_ll);
	}
}
